async function createTestMachine() {
    const description = "q1 1 0 R q2\n q2 0 1 R q1\nq2 b b H halt";
    const initialTape = "101b";
    const initialState = "q1";
    const blankSymbol = "b";  // 添加 BLANK符号

    const response = await fetch("/create_machine", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            "instructions": description,
            "tape": initialTape,
            "state": initialState,
            "blank_symbol": blankSymbol  // 传递 blank_symbol
        })
    });
    const data = await response.json();
    const machineId = data.id; // Assuming the response includes the machine ID
    createNewMachineUI(machineId, initialTape, initialState, 0, description, data.cycles || 0);
}

async function fetchAllMachines() {
    const response = await fetch("/machines");
    if (!response.ok) {
        console.error("Failed to fetch machine data");
        return;
    }

    const machines = await response.json(); // This should now be an object
    const machineIds = Object.keys(machines); // Extract machine IDs from the object

    if (machineIds.length === 0) {
        document.querySelector('.main-content').innerHTML = '<button class="button" onclick="add()">添加一个图灵机</button>';
        return;
    }

    const existingEntries = Array.from(document.querySelectorAll('.entry')).map(entry => entry.querySelector('.sequence-number').textContent.trim());

    // Delete entries not in machineIds
    existingEntries.forEach(id => {
        if (!machineIds.includes(id)) {
            removeMachineUI(id);
        }
    });

    // Add or update entries
    for (const id of machineIds) {
        const machineData = machines[id]; // Get machine data by ID
        if (existingEntries.includes(id)) {
            updateUI(id, machineData);
        } else {
            createNewMachineUI(id, machineData.tape, machineData.state, machineData.head_position, machineData.cycles || 0);
        }
    }
}

function removeMachineUI(id) {
    const entry = document.querySelector(`.entry[data-id="${id}"]`);
    if (entry) {
        entry.remove();
    }
}

// createTestMachine();
// Call this function to fetch and display all machines
fetchAllMachines();
setInterval(fetchAllMachines, 1000);

async function createMachine() {
    const description = document.getElementById("description").value;
    const initialTape = document.getElementById("initialTape").value;
    const initialState = document.getElementById("initialState").value;
    const blankSymbol = document.getElementById("blankSymbol").value;  // 获取 BLANK符号

    const response = await fetch("/create_machine", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            "instructions": description,
            "tape": initialTape,
            "state": initialState,
            "blank_symbol": blankSymbol  // 传递 blank_symbol
        })
    });
    const data = await response.json();
    const machineId = data.id; // Assuming the response includes the machine ID
    createNewMachineUI(machineId, initialTape, initialState, 0, data.cycles || 0);
    updateUI(machineId, {
        state: initialState,
        tape: initialTape,
        head_position: 0,
        cycles: data.cycles || 0
    });
}

async function updateMachine(id) {
    const description = document.getElementById("description").value;
    const initialTape = document.getElementById("initialTape").value;
    const initialState = document.getElementById("initialState").value;
    const blankSymbol = document.getElementById("blankSymbol").value;  // 获取 BLANK符号

    const response = await fetch("/update_machine/" + id, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            "instructions": description,
            "tape": initialTape,
            "state": initialState,
            "blank_symbol": blankSymbol  // 传递 blank_symbol
        })
    });
    const data = await response.json();
    updateUI(id, data);
}
